package me.numark.activities;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import butterknife.Bind;
import me.numark.R;
import me.numark.fragments.DiscoverFragment;
import me.numark.fragments.FeedFragment;
import me.numark.fragments.FriendsFragment;
import me.numark.fragments.NoticeFragment;
import me.numark.fragments.ProfileFragment;
import me.numark.model.User;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.Settings;

/**
 * Created by ytian on 15/8/1.
 */
public class AddFriendsActivity extends AuthenticatorActivity implements View.OnClickListener {
    @Bind(R.id.right_image)
    ImageView rightImage;

    @Bind(R.id.right_text)
    TextView rightText;

    @Bind(R.id.numark_friends)
    TextView numarkFriends;

    @Bind(R.id.contacts_friends)
    TextView contactsFriends;

    @Bind(R.id.weibo_friends)
    TextView weiboFriends;

    @Bind(R.id.source_group)
    LinearLayout sourceGroup;

    @Bind(R.id.fragment)
    FrameLayout fragment;

    @Bind(R.id.left_divider)
    View leftDivider;

    private String weiboId, weiboToken;
    private SparseArray<FriendsFragment> fragments = new SparseArray<FriendsFragment>(3);
    private int userId;

    private FriendsFragment mFragment;
    private int currentFragmentIndex;
    boolean isFromLogin = false;
    boolean isFromSetting = false;
    private TextView[] tabButtons = new TextView[3];
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_add_friends;
        super.onCreate(savedInstanceState);
        isFromSetting = getIntent().getBooleanExtra(SettingsActivity.EXTRA_FROM_SETTING, false);
        isFromLogin = getIntent().getBooleanExtra(LogInActivity.EXTRA_FROM_LOGIN,false);
        initParams(getIntent());
        initView();
        //initFragment();
    }

   /* private void initFragment() {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        mFragment = FriendsFragment.newInstance(userId, isFromSetting,FriendsFragment.TYPE_FIND);
        ft.add(R.id.fragment, mFragment);
        ft.show(mFragment);
        ft.commitAllowingStateLoss();
    }*/

    private void initView() {
        backInToolbar.setVisibility(isFromSetting ? View.VISIBLE : View.INVISIBLE);
        contactsFriends.setOnClickListener(this);
        numarkFriends.setOnClickListener(this);
        weiboFriends.setOnClickListener(this);
        tabButtons[0] = numarkFriends;
        tabButtons[1] = contactsFriends;
        tabButtons[2] = weiboFriends;
        if (isFromSetting) {
            titleTextView.setText(R.string.setting_friends);
            numarkFriends.setVisibility(View.GONE);
        } else {
            titleTextView.setText(R.string.possibly_interested_people);
            switchFragments(0, false);
        }
        rightText.setText(R.string.finish);
        rightText.setVisibility(View.VISIBLE);
        rightText.setOnClickListener(this);
        //numarkFriends.setSelected(true);



    }

    private void initParams(Intent intent) {
        if (Global.isLoggedIn()) {
            userId = Global.getCurrentUid();
        } else {
            userId = intent.getIntExtra("user_id", 0);
            weiboId = intent.getStringExtra("weibo_id");
            weiboToken = intent.getStringExtra("weibo_token");
        }
    }

    @Override
    public void onBackPressed() {
        if (Global.isLoggedIn()) {
            super.onBackPressed();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_text:
                if (!isFromSetting && !isFromLogin){
                    User user = Global.currentUser;
                    Settings.delUser(String.valueOf(user.uid));
                    //Global.currentUser = null;
                }
                mFragment.addFriends();
                break;
            case R.id.numark_friends:
                switchFragments(0,true);
               /* if (!numarkFriends.isSelected()){
                    contactsFriends.setSelected(false);
                    weiboFriends.setSelected(false);
                    numarkFriends.setSelected(true);
                }*/
                break;
            case R.id.contacts_friends:
               /* if (!contactsFriends.isSelected()) {
                    contactsFriends.setSelected(true);
                    weiboFriends.setSelected(false);
                    numarkFriends.setSelected(false);
                    askVisitContacts();
                }*/
                askVisitContacts();

                break;
            case R.id.weibo_friends:
                /*if (weiboFriends.isSelected()) {
                    return;
                }
                if (isWeiboLoggedIn()) {
                    askLogInWeibo();
                } else {
                    weiboFriends.setSelected(true);
                    contactsFriends.setSelected(false);
                    numarkFriends.setSelected(false);
                    mFragment.loadWithWeibo(weiboId, weiboToken);
                }*/
                if (isWeiboLoggedIn()){
                    askLogInWeibo();
                }else {
                    switchFragments(2, true);
                }
                break;
        }
    }
    public void switchFragments(int index,boolean init){
        if (currentFragmentIndex == index && init) {
            return;
        }
        tabButtons[currentFragmentIndex].setSelected(false);
        Fragment oldFragment = fragments.get(currentFragmentIndex);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (oldFragment != null)
            ft.hide(oldFragment);

        currentFragmentIndex = index;
        tabButtons[currentFragmentIndex].setSelected(true);
        FriendsFragment newFragment = fragments.get(currentFragmentIndex);
        if (newFragment == null) {
            switch (currentFragmentIndex) {
                case 0:
                    newFragment = FriendsFragment.newInstance(userId, isFromSetting,FriendsFragment.TYPE_FIND_SITE);
                    break;
                case 1:
                    newFragment = FriendsFragment.newInstance(Global.isLoggedIn()?Global.getCurrentUid():userId,isFromSetting,FriendsFragment.TYPE_FIND_CONTACTS);
                    newFragment.loadWithContacts();
                    break;
                case 2:
                    newFragment = FriendsFragment.newInstance(userId,isFromSetting,FriendsFragment.TYPE_FIND_WEIBO);
                    newFragment.loadWithWeibo(weiboId,weiboToken);
                    break;
            }
            fragments.put(currentFragmentIndex, newFragment);
        }
        if (newFragment != null) {
            if (!newFragment.isAdded()) {
                ft.add(R.id.fragment, newFragment, String.valueOf(currentFragmentIndex));
            }
            ft.show(newFragment);
        }
        mFragment = (FriendsFragment)newFragment;
        ft.commitAllowingStateLoss();
    }

    private boolean isWeiboLoggedIn() {
        return TextUtils.isEmpty(weiboId) || TextUtils.isEmpty(weiboToken);
    }

    private void askVisitContacts() {
        new AlertDialog.Builder(this).setTitle(R.string.will_visit_contacts).setMessage(R.string
                .visit_contacts_msg).setPositiveButton(R.string.good, new DialogInterface
                .OnClickListener() {


            @Override
            public void onClick(DialogInterface dialog, int which) {
                /*contactsFriends.setSelected(true);

                mFragment.loadWithContacts();*/
                switchFragments(1, true);
            }
        }).setNegativeButton(R.string.not_allow, null).show();
    }

    private void askLogInWeibo() {
        if (isWeiboLoggedIn()) {
            new AlertDialog.Builder(this).setTitle(R.string.ask_access_weibo).setPositiveButton(R
                    .string.good, new DialogInterface.OnClickListener() {


                @Override
                public void onClick(DialogInterface dialog, int which) {
                    weiboLogIn();
                }
            }).setNegativeButton(R.string.not_allow, null).show();
        } else {
            switchFragments(2, true);
        }
    }

    private void weiboLogIn() {
        mSsoHandler.authorize(this);
    }

    @Override
    protected void afterLogin(int type, String uid, String token) {
        if (type == VALUE_SINA) {
            weiboId = uid;
            weiboToken = token;
            weiboFriends.setSelected(true);
            mFragment.loadWithWeibo(weiboId, weiboToken);
        }
    }
}
